var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var io = require('socket.io')();

var db = require('./db');
var dbcookie = require('./db/cookie');

var routes = require('./routes/index');
var articles = require('./routes/articles');
var log = require('./routes/log');
var map = require('./routes/map');
var user = require('./routes/user');
var userhome = require('./routes/userhome');
var video = require('./routes/video');
var select = require('./routes/select');
var ces = require('./routes/ces');
var admin = require('./routes/admin');
var upload = require('./routes/upload');
var app = express();



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);  
app.set('view engine', 'html');


app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json({"limit":"10240kb"}));
app.use(bodyParser.urlencoded({"limit":"10240kb"}));
app.use(cookieParser());
app.use(session({
    secret:'keyKeY',
    resave:false,
    name:'info',
    saveUninitialized:true,
    cookie:{
        secure:false,
        maxAge:66666666
    }
}));

app.use(db);
app.use(dbcookie);

app.use('/', routes);
app.use('/articles', articles);
app.use('/log', log);
app.use('/map', map);
app.use('/video', video);
app.use('/user', user);
app.use('/userhome', userhome);
app.use('/select', select);
app.use('/ces', ces);
app.use('/admin', admin);
app.use('/upload',upload);
/// catch 404 and forwarding to error handler
/*
*   配置404页面
*/
app.use(function(req, res, next) {
    res.status(404).render('404',{});
});

// app.use(function(req, res, next) {
//     var err = new Error('Not Found');
//     err.status = 404;
//     next(err);
// });

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.io = io;
var msgUsers =  new Object(); 
io.use(function(socket, next){
    next();
});

io.sockets.on('connection', function (socket) {


    socket.on("join", function (msg) {

        socket.name = msg.name;
        if(msg.name in msgUsers){
             msgUsers[msg.name].push(socket); 
        }else{
             msgUsers[msg.name] = [socket];
        }

    });

    socket.on("msg", function (msg) {
        // socket.broadcast.emit("msg",msg);
        if(msg.toname in msgUsers){
            if (msgUsers[msg.toname].length>0) {
                for(var i = 0; i<msgUsers[msg.toname].length;i++) {
                    msgUsers[msg.toname][i].emit("msg",msg);
                    msgUsers[msg.toname][i].emit("news",{'msg':"您收到一条来自"+socket.name+"的私信"});
                }
            } else {
                socket.emit("msg",{'msg':"离线状态 稍后回复!(> - < )!"});
            }
        }else{
             socket.emit("msg",{'msg':"离线状态 稍后回复!(> - < )!"});
        }
    });

    socket.on('disconnect', function() {
        if(socket.name){
            for(var i=0; i<msgUsers[socket.name].length; i++) {
                if(msgUsers[socket.name][i] == socket) {
                  msgUsers[socket.name].splice(i, 1);
                  break;
                }
            }
        }
        console.log("---over---");
    });

});



module.exports = app;
